package com.flower.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.flower.domain.dto.LoginDto;
import com.flower.domain.dto.buyer.PageBuyerDto;
import com.flower.domain.entity.Buyer;
import com.flower.domain.entity.Shop;
import com.flower.domain.vo.admin.BuyerVO;
import com.flower.mapper.ShopMapper;
import com.flower.service.BuyerService;
import com.flower.mapper.BuyerMapper;
import com.flower.utils.BeanCopyUtils;
import com.flower.utils.Md5Util;
import com.flower.domain.vo.PageVO;
import com.flower.utils.UserContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 86178
 * @description 针对表【buyer】的数据库操作Service实现
 * @createDate 2025-02-17 20:54:03
 */
@Service
public class BuyerServiceImpl extends ServiceImpl<BuyerMapper, Buyer>
        implements BuyerService {

    @Autowired
    private BuyerMapper buyerMapper;
    
    @Autowired
    private ShopMapper shopMapper;

    @Override
    public Buyer login(LoginDto loginDto) {
        // 根据用户名查询用户信息
        Buyer buyer = buyerMapper.selectOne(new QueryWrapper<Buyer>().eq("username", loginDto.getUsername()));
        // 判断用户是否存在
        if (buyer != null) {
            // 判断密码是否正确
            if (Md5Util.checkPassword(loginDto.getPassword(), buyer.getPassword())) {
                return buyer;
            }
        }
        return null;
    }

    @Override
    public PageVO<Buyer> pageList(PageBuyerDto pageBuyerDto) {
        // 构建查询条件
        LambdaQueryWrapper<Buyer> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加关键字搜索条件
        if (StringUtils.isNotBlank(pageBuyerDto.getKeyword())) {
            queryWrapper.like(Buyer::getUsername, pageBuyerDto.getKeyword())
                    .or()
                    .like(Buyer::getTelephone, pageBuyerDto.getKeyword());
        }
        
        // 添加排序条件
        queryWrapper.orderByDesc(Buyer::getCreateTime);
        
        // 执行分页查询
        Page<Buyer> page = new Page<>(pageBuyerDto.getPageNumber(), pageBuyerDto.getPageSize());
        Page<Buyer> buyerPage = buyerMapper.selectPage(page, queryWrapper);
        
        // 构建返回结果
        PageVO<Buyer> pageVO = new PageVO<>();
        BeanUtils.copyProperties(buyerPage, pageVO);
        return pageVO;
    }
    
    @Override
    public PageVO<BuyerVO> pageListWithShopInfo(PageBuyerDto pageBuyerDto) {
        // 构建查询条件
        LambdaQueryWrapper<Buyer> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加关键字搜索条件
        if (StringUtils.isNotBlank(pageBuyerDto.getKeyword())) {
            queryWrapper.like(Buyer::getUsername, pageBuyerDto.getKeyword())
                    .or()
                    .like(Buyer::getTelephone, pageBuyerDto.getKeyword());
        }
        
        // 添加排序条件
        queryWrapper.orderByDesc(Buyer::getCreateTime);
        
        // 执行分页查询
        Page<Buyer> page = new Page<>(pageBuyerDto.getPageNumber(), pageBuyerDto.getPageSize());
        Page<Buyer> buyerPage = buyerMapper.selectPage(page, queryWrapper);
        
        // 构建返回结果
        PageVO<BuyerVO> pageVO = new PageVO<>();
        
        List<BuyerVO> buyerVOList = new ArrayList<>();
        
        // 如果没有数据，直接返回空列表
        if (buyerPage.getRecords().isEmpty()) {
            pageVO.setRecords(buyerVOList);
            pageVO.setCurrent(buyerPage.getCurrent());
            pageVO.setSize(buyerPage.getSize());
            pageVO.setTotal(buyerPage.getTotal());
            return pageVO;
        }
        
        // 获取所有买家ID
        List<Integer> buyerIds = buyerPage.getRecords().stream()
                .map(Buyer::getBuyerId)
                .collect(Collectors.toList());
        
        // 查询所有买家对应的店铺信息
        LambdaQueryWrapper<Shop> shopQueryWrapper = new LambdaQueryWrapper<>();
        shopQueryWrapper.in(Shop::getBuyerId, buyerIds);
        List<Shop> shops = shopMapper.selectList(shopQueryWrapper);
        
        // 将店铺按买家ID分组
        Map<Integer, Shop> buyerShopMap = shops.stream()
                .collect(Collectors.toMap(Shop::getBuyerId, shop -> shop, (s1, s2) -> s1));
        
        // 构建BuyerVO列表
        for (Buyer buyer : buyerPage.getRecords()) {
            BuyerVO buyerVO = new BuyerVO();
            BeanUtils.copyProperties(buyer, buyerVO);
            
            // 设置店铺信息
            Shop shop = buyerShopMap.get(buyer.getBuyerId());
            if (shop != null) {
                buyerVO.setShopId(shop.getShopId());
                buyerVO.setHasShop(true);
                buyerVO.setIsOpen(shop.getIsOpen());
            } else {
                buyerVO.setHasShop(false);
            }
            
            buyerVOList.add(buyerVO);
        }
        
        pageVO.setRecords(buyerVOList);
        pageVO.setCurrent(buyerPage.getCurrent());
        pageVO.setSize(buyerPage.getSize());
        pageVO.setTotal(buyerPage.getTotal());
        
        return pageVO;
    }

    @Override
    public Buyer findBuyerByEmail(String email) {
        // 根据邮箱查询用户信息
        return buyerMapper.selectOne(new QueryWrapper<Buyer>().eq("email", email));
    }

    @Override
    public Buyer getUserInfo() {
        return this.getById(UserContext.getUserId());
    }

    @Override
    @Transactional
    public void updateUserInfo(Buyer buyer) {
        buyer.setBuyerId(UserContext.getUserId().intValue());

        // 验证手机号是否被占用
        if (isPhoneExist(buyer.getTelephone(), buyer.getBuyerId())) {
            throw new RuntimeException("手机号已被使用");
        }
        
        // 验证邮箱是否被占用
        if (isEmailExist(buyer.getEmail(), buyer.getBuyerId())) {
            throw new RuntimeException("邮箱已被使用");
        }
        
        this.updateById(buyer);
    }

    // 验证手机号是否被占用
    private boolean isPhoneExist(String phone, Integer excludeId) {
        return this.lambdaQuery()
                .eq(Buyer::getTelephone, phone)
                .ne(Buyer::getBuyerId, excludeId)
                .count() > 0;
    }

    // 验证邮箱是否被占用
    private boolean isEmailExist(String email, Integer excludeId) {
        return this.lambdaQuery()
                .eq(Buyer::getEmail, email)
                .ne(Buyer::getBuyerId, excludeId)
                .count() > 0;
    }

    @Override
    public Page<Buyer> getBuyerList(String keyword, Integer page, Integer size) {
        Page<Buyer> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<Buyer> wrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.isNotBlank(keyword)) {
            wrapper.like(Buyer::getUsername, keyword)
                  .or()
                  .like(Buyer::getUsername, keyword)
                  .or()
                  .like(Buyer::getTelephone, keyword);
        }
        
        wrapper.orderByDesc(Buyer::getCreateTime);
        return this.page(pageParam, wrapper);
    }

    @Override
    public void addBuyer(Buyer buyer) {
        // 设置默认值
        buyer.setCreateTime(LocalDateTime.now());
        buyer.setUpdateTime(LocalDateTime.now());
        
        // 保存购买者信息
        this.save(buyer);
    }

    @Override
    public void updateBuyer(Buyer buyer) {
        // 更新修改时间
        buyer.setUpdateTime(LocalDateTime.now());
        
        // 更新购买者信息
        this.updateById(buyer);
    }

    @Override
    public void deleteBuyer(Integer id) {
        this.removeById(id);
    }

    @Override
    public Buyer getBuyerById(Integer id) {
        return this.getById(id);
    }

    @Override
    public boolean isUsernameExists(String username) {
        return isUsernameExists(username, null);
    }

    @Override
    public boolean isUsernameExists(String username, Integer excludeId) {
        LambdaQueryWrapper<Buyer> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Buyer::getUsername, username);
        if (excludeId != null) {
            wrapper.ne(Buyer::getBuyerId, excludeId);
        }
        return this.count(wrapper) > 0;
    }
}




